﻿using BCCommon;
using BCEntity.TMS.User.UserAddressBook;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCData.TMS.User.UserAddressBook
{
    public class UserAddressBookData : IUserAddressBookData
    {
        private readonly IDatabaseContext database;

        private readonly string QUERY = @"SELECT
		                                UserAddressBookId,
		                                UserId,
		                                ContactName,
		                                ContactPhone,
		                                ProvinceCode,
		                                CityCode,
		                                CountyCode,
		                                Address,
		                                Longitude,
		                                Latitude,
		                                IsDefault,
		                                CreateTime,
		                                UpdateTime 
                                    FROM
                                        UserAddressBook";

        private readonly string QUERY_JOIN = @"SELECT
		                                A.UserAddressBookId,
		                                A.UserId,
		                                A.ContactName,
		                                A.ContactPhone,
		                                A.ProvinceCode,
		                                A.CityCode,
		                                A.CountyCode,
		                                A.Address,
		                                A.Longitude,
		                                A.Latitude,
		                                A.IsDefault,
		                                A.CreateTime,
		                                A.UpdateTime,
                                        B.ProvinceName,
		                                B.CityName,
		                                B.CountyName 
                                    FROM
                                        UserAddressBook A 
                                        INNER JOIN County B ON A.ProvinceCode = B.ProvinceCode AND A.CityCode = B.CityCode AND A.CountyCode = B.CountyCode";

        #region 构造函数
        public UserAddressBookData(IDatabaseContext database)
        {
            this.database = database;
        }
        #endregion

        #region InsertAsync
        /// <summary>
        /// 添加用户地址薄
        /// </summary>
        /// <param name="entity">用户地址薄信息</param>
        /// <returns></returns>
        public async Task<UserAddressBookEntity> InsertAsync(UserAddressBookEntity entity)
        {
            return await this.database.Master.InsertAsync(entity, database.Transaction);
        }
        #endregion

        #region updateAsync
        /// <summary>
        /// 修改用户地址薄记录
        /// </summary>
        /// <param name="userAddressBookEntity"></param>
        /// <returns></returns>
        public async Task<UserAddressBookEntity> UpdateAsync(UserAddressBookEntity entity)
        {
            return await this.database.Master.UpdateAsync(entity, database.Transaction);
        }
        #endregion 

        #region Delete
        /// <summary>
        /// 删除用户地址薄记录
        /// </summary>
        /// <param name="userAddressBookId"></param>
        /// <returns></returns>
        public async Task<int> DeleteAsync(long userAddressBookId)
        {
            return await this.database.Master.ExecuteAsync("DELETE FROM UserAddressBook WHERE UserAddressBookId = ?UserAddressBookId", new { userAddressBookId });
        }
        #endregion

        #region GetById
        /// <summary>
        /// 获取用户地址薄记录
        /// </summary>
        /// <param name="userAddressBookId"></param>
        /// <returns></returns>
        public async Task<UserAddressBookViewEntity> GetEntityAsync(long userAddressBookId)
        {
            return await this.database.Slave.QueryEntityAsync<UserAddressBookViewEntity>($"{QUERY_JOIN} WHERE A.UserAddressBookId = ?UserAddressBookId", new { userAddressBookId });
        }
        #endregion

        public async Task<int> UpdateIsDefault(long userId)
        {
            return await database.Master.ExecuteAsync("UPDATE UserAddressBook SET IsDefault = 0 WHERE UserId = ?UserId", new { userId }, database.Transaction);
        }

        public async Task<(IEnumerable<UserAddressBookViewEntity>, int)> Query(long userId, int pageIndex, int pageSize)
        {
            DynamicParameters parameters = new DynamicParameters();
            parameters.Add("?UserId", userId, DbType.Int64);
            string sql = string.Format(@"{0} WHERE A.UserId = ?UserId ORDER BY A.IsDefault DESC,A.UserAddressBookId DESC LIMIT {1},{2};
                            SELECT COUNT(1) FROM UserAddressBook WHERE UserId = ?UserId",
                            QUERY_JOIN,
                            (pageIndex - 1) * pageSize,
                            pageSize);
            return await database.Slave.QueryPageableListAsync<UserAddressBookViewEntity>(sql, parameters);
        }

        public async Task<IEnumerable<UserAddressBookViewEntity>> GetList(long userId)
        {
            return await database.Slave.QueryAsync<UserAddressBookViewEntity>($"{QUERY_JOIN} WHERE A.UserId = ?UserId ORDER BY A.IsDefault DESC,A.UserAddressBookId DESC", new { userId });
        }
    }
}
